package com.jiezhuo.easyExcel.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.jiezhuo.easyExcel.DomeMap;
import com.jiezhuo.easyExcel.service.ServiceBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


public class

DomeListen extends AnalysisEventListener<DomeMap> {
    List<DomeMap> list = new ArrayList<>();
    /**
     * 单次缓存的数据量
     */
    public static final int BATCH_COUNT = 100;
     ServiceBean dataService;
    public DomeListen(){

     }
    public DomeListen(ServiceBean dataService){
        this.dataService =dataService;
    }
    private static Logger logger = LoggerFactory.getLogger(DomeListen.class);
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        super.onException(exception, context);
    }

    @Override
    public void invoke(DomeMap domeMap, AnalysisContext analysisContext) {
        logger.info("解析到一条数据:{}", domeMap.toString());
        list.add(domeMap);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
             list.clear();
        }
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        super.extra(extra, context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        logger.info("所有数据解析完成！");
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return super.hasNext(context);
    }

    private void saveData() {
        logger.info("{}条数据，开始存储数据库！", list.size());
        dataService.saveBatchModel(list);
        logger.info("存储数据库成功！");
    }
}
